package com.password.util;

import java.io.File;

import org.ehcache.CachePersistenceException;
import org.ehcache.PersistentUserManagedCache;
import org.ehcache.Status;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.builders.UserManagedCacheBuilder;
import org.ehcache.config.units.EntryUnit;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.core.spi.service.LocalPersistenceService;
import org.ehcache.impl.config.persistence.DefaultPersistenceConfiguration;
import org.ehcache.impl.config.persistence.UserManagedPersistenceContext;
import org.ehcache.impl.persistence.DefaultLocalPersistenceService;

import com.password.entity.User;

/**
 * 缓存相关工具类，该工具类中的CacheManager是一个懒汉模式类单例
 * 
 * @author yzh
 * @date 2020年5月26日
 *
 */
public class CacheUtil {
	private CacheUtil() {
	}

	private static class CacheUtilBuilder {
		private static UserManagedCacheBuilder<String, User, PersistentUserManagedCache<String, User>> userCacheBuilder;

		static {
			// 分配1000个用户，10M的磁盘存储空间给用户
			userCacheBuilder = getPersiterCacheBuilder("userInfo", String.class, User.class, 1000L, 10L);
		}

		/**
		 * 
		 * @author yzh
		 * @date 2020年5月26日
		 * 
		 * @param <T>
		 * @param <V>
		 * @param cacheName      缓存的名称
		 * @param key            缓存的key值类型
		 * @param value          缓存的value类型
		 * @param heapEntitySize 缓存在堆中的大小,单位为Entity
		 * @param diskSize       缓存在磁盘中的大小，单位为MB
		 * @return
		 */
		private static <T, V> UserManagedCacheBuilder<T, V, PersistentUserManagedCache<T, V>> getPersiterCacheBuilder(
				String cacheName, Class<T> key, Class<V> value, Long heapEntitySize, Long diskSize) {
			LocalPersistenceService persistenceService = new DefaultLocalPersistenceService(
					new DefaultPersistenceConfiguration(new File(SystemConfig.getContextPath(), cacheName)));
			UserManagedCacheBuilder<T, V, PersistentUserManagedCache<T, V>> userCacheBuilder = UserManagedCacheBuilder
					.newUserManagedCacheBuilder(key, value)
					.with(new UserManagedPersistenceContext<>(cacheName, persistenceService))
					.withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder()
							.heap(heapEntitySize, EntryUnit.ENTRIES).disk(diskSize, MemoryUnit.MB, true));
			return userCacheBuilder;
		}
	}

	public static PersistentUserManagedCache<String, User> getUserCache() {
		return CacheUtilBuilder.userCacheBuilder.build(true);
	}

}
